package synchronized_;


/*
*实现：线程安全的方法
*
* 方式二：同步方法
* 将synchronized写到方法上
*
* */
public class MySynchronizedDemo2  extends Thread {
    private static int ticket = 100;

    @Override
    public void run() {
        while (true){
            if (ticket>0){
                show();
            }else {
                break;
            }

        }
    }

    //private   synchronized void show() { 错误的写法，这时锁对象为（this）当前对象，但是当前对象对于三个线程来说不是唯一的
    private  static synchronized void show() {  //正确的写法 因为方法为静态的，因此，锁对象为MySynchronizedDemo2.class
        if (ticket>0){
            System.out.println(Thread.currentThread().getName()+"出票："+ticket);
            ticket--;
        }
    }
}

class TestThreadDemo3{
    public static void main(String[] args) {

        MySynchronizedDemo2 threadDemo1 = new MySynchronizedDemo2();
        MySynchronizedDemo2 threadDemo2 = new MySynchronizedDemo2();
        MySynchronizedDemo2 threadDemo3 = new MySynchronizedDemo2();

        threadDemo1.setName("窗口一");
        threadDemo2.setName("窗口二");
        threadDemo3.setName("窗口三");
        threadDemo1.start();
        threadDemo2.start();
        threadDemo3.start();
    }
}
